import axios from "axios"
import vm from "../main"
import { JSEncrypt } from "jsencrypt"
import qs from "qs"

const util = {}

// read env from configs file
const env = window["$env"] ? window["$env"] : process.env.NODE_ENV
console.log(env)
util.fileIP = 'https://219.139.130.110:6009/download' //上传模块
//util.baseIP = 'https://219.139.130.110:6009/api-elevator-sup' //登录模块
//util.baseIP = 'https://219.139.130.110:6009/api-elevator-sup'
util.baseIP = 'http://localhost:8083/api-elevator-sup'
//util.baseIP = '/api-elevator-sup' //登录模块
// util.baseIP = 'http://localhost:8084/api-elevator-sup' //登录模块
util.baseRescue = 'http://yclift.gateway.devops.com/liftRescue'  //应急模块
// 将需要外挂文件覆盖的属性写在该函数执行前
loadConfigs()

//事件格式处理函数
util.dateFormat = function (fmt, date) {
  let ret
  let opt = {
    "Y+": date.getFullYear().toString(), // 年
    "m+": (date.getMonth() + 1).toString(), // 月
    "d+": date.getDate().toString(), // 日
    "H+": date.getHours().toString(), // 时
    "M+": date.getMinutes().toString(), // 分
    "S+": date.getSeconds().toString() // 秒
    // 有其他格式化字符需求可以继续添加，必须转化成字符串
  }
  for (let k in opt) {
    ret = new RegExp("(" + k + ")").exec(fmt)
    if (ret) {
      fmt = fmt.replace(
        ret[1],
        ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0")
      )
    }
  }
  return fmt
}

util.numFormatter = function (num) {
  let res = num
  if (num && num !== null) {
    res = num.toString().replace(/\d+/, (n) => {
      return n.replace(/(\d)(?=(\d{3})+$)/g, ($1) => {
        return $1 + ','
      })
    })
  }
  return res
}




util.http = axios.create({
  //baseURL: 'https://219.139.130.110:6009/api-elevator-sup',
  //baseURL: 'https://219.139.130.110:6009/api-elevator-sup',
   baseURL: 'http://localhost:8083/api-elevator-sup',

  timeout: 36000000,
})

// http请求拦截
util.http.interceptors.request.use(
  function (config) {
    config.headers.Authorization = localStorage.token
    return config
  },
  function (error) {
    // 请求失败的处理
    return Promise.reject(error)
  }
)

// http响应拦截
util.http.interceptors.response.use(
  function (res) {
    // console.log(res)
    // 在这里对返回的数据进行处理
    if (!res.config.url.includes("refreshToken")) {
      // 记录ajax调用的时间
      sessionStorage.lastHttpRequestTime = +new Date()
    }

    switch (res.data.code) {
      case 401:
        if (vm.$route.name !== "login") {
          vm.$Message.warning({
            content: "身份认证信息已失效，请重新登录。",
            duration: 1,
            onClose: () => {
              vm.$router.push({
                name: "login"
              })
            }
          })
        }
        break
      case 4007:
        if (vm.$route.name !== "login") {
          vm.$Message.warning({
            content: "身份认证信息已失效，请重新登录。",
            duration: 1,
            onClose: () => {
              vm.$router.push({
                name: "login"
              })
            }
          })
        }
        break

    }


    return res
  },
  function (error) {
    console.log(error)
    // Do something with response error
    if (error.response) {
      switch (error.response.code) {
        case 401:
          if (vm.$route.name !== "login") {
            vm.$Message.warning({
              content: "身份认证信息已失效，请重新登录。",
              duration: 2,
              onClose: () => {
                vm.$router.push({
                  name: "login"
                })
              }
            })
          } else {
            return Promise.reject(error)
          }
          break
        case 403:
          vm.$Message.warning({
            content: error.response.data.message,
            duration: 3
          })
          break
        case 4007:
          if (vm.$route.name !== "login") {
            vm.$Message.warning({
              content: "身份认证信息已失效，请重新登录。",
              duration: 2,
              onClose: () => {
                vm.$router.push({
                  name: "login"
                })
              }
            })
          } else {
            return Promise.reject(error)
          }
          break
        default:
          return Promise.reject(error)
      }
    } else if (error.message) {
      if (error.message === "Network Error") {
        vm.$Message.error("网络连接错误，请检查网络环境！")
      } else if (error.message.indexOf("timeout") >= 0) {
        vm.$Message.error("网络连接超时，请重试！")
      } else {
        vm.$Message.error(error.message)
      }
    } else {
      vm.$Message.error("知识盲区的错误，联系程序员小哥哥吧！")
    }
  }
)

/**
 * 将请求参数转换为URLSearchParams格式
 * post、put等，axios默认使用json格式，如果需要使用form格式的，调用该函数进行转换
 * data: object
 */
util.formUrlencoded = function (data) {
  return qs.stringify(data)
}

// 定位新打开的页面在pageOpenedList中位置
util.indexOfCurrentPageOpened = function (name, pageOpenedList) {
  for (let index = 0; index < pageOpenedList.length; index++) {
    if (pageOpenedList[index].name === name) {
      return index
    }
  }
  return -1
}

// 初始化header中的面包屑路径
util.initCurrentPath = function (route, routesTree) {
  if (!(routesTree instanceof Array) || routesTree.length === 0) {
    return []
  }
  if (route.name === "home") {
    return []
  }
  let res = []
  for (let item of routesTree) {
    if (item.children && item.children.length > 0) {
      const temp = getPathOfChild(route, item.children)
      if (temp.done) {
        res = temp.value
        if (item.type === "menu1") {
          res.splice(0, 0, item.title)
        }
        break
      }
    }
  }
  return res
}

function getPathOfChild (route, sourceArr) {
  let res = {
    value: [],
    done: false
  }
  if (!(sourceArr instanceof Array) || sourceArr.length === 0) {
    return res
  }
  const name = route.name
  for (let item of sourceArr) {
    const temp = []
    temp.push(item.title)
    if (name === item.name) {
      return {
        value: temp,
        done: true
      }
    } else {
      if (item.children && item.children.length > 0) {
        const tempRes = getPathOfChild(route, item.children)
        if (tempRes.done) {
          return {
            value: temp.concat(tempRes.value),
            done: true
          }
        }
      }
    }
  }
  return res
}

// 数据加密方法
//const rsaPubKey = ''
const rsaPubKey =
  "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgUQ6whp6I2PqtPvWZntZFcmmJ21P6LKYpkoHPGKST/oveEkBULp/XvxXWMGInbyGJQ5awJ5wIws8Nkl7yQMDm3aQb49zIFl+Eaf0D+8ADvMVzFY/frbkVpn1wON5tLFxf3Db4yQtveiTUlc3k2r2/dfYTlLhbXlz/pduRDF3pjpV3v7n/2gjVz47B+HdvFOczwyEguOnOYYik3y4BXQ7tPL44enYsbvZRViN9S0JqnDaoxjW85FmdiQeztQgzzesMX+HxY11JxJ/Tbxl7h6NrLGwNI1ZEgc5sQUX8PgTGwfO3zp3WUVcjwHNwwm06lbAryYsVFoSgmdMyhbUw+LkiQIDAQAB"

util.encryptPassword = function (str) {
  if (rsaPubKey) {
    // 对密码进行加密
    let encryptor = new JSEncrypt() // 新建JSEncrypt对象
    encryptor.setPublicKey(rsaPubKey) // 设置公钥
    return encryptor.encrypt(str) // 加密
  } else {
    return str
  }
}

util.getMenuList = function (menus) {
  const tempList = []
  menus.forEach(ele => {
    if (ele.type && ele.type === "menu") {
      const tempObj = {}
      if (ele.children) {
        tempObj.children = util.getMenuList(ele.children)
      }
      tempObj.name = ele.name
      tempObj.icon = ele.icon || "ios-cube-outline"
      tempObj.title = ele.title
      tempList.push(tempObj)
    }
  })
  return tempList
}

util.getMenuRoutes = function (tree) {
  const menuRoutes = buildMenuRoutesStep1(tree)
  buildMenuRoutesStep2(menuRoutes)
  buildMenuRoutesStep3(menuRoutes)
  return menuRoutes
}

function buildMenuRoutesStep1 (menus) {
  const tempRoutes = []
  menus.forEach(ele => {
    const tempObj = {}
    if (ele.children) {
      tempObj.children = buildMenuRoutesStep1(ele.children)
    }
    tempObj.path = ele.path
    tempObj.name = ele.name
    tempObj.meta = {
      title: ele.title
    }
    tempObj.component = ele.component
    tempRoutes.push(tempObj)
  })
  return tempRoutes
}

function buildMenuRoutesStep2 (routes, root) {
  routes.forEach(ele => {
    if (ele.children) {
      // rootEle保存根节点对象
      const rootEle = root || ele
      buildMenuRoutesStep2(ele.children, rootEle)
      if (JSON.stringify(ele) !== JSON.stringify(rootEle)) {
        if (!ele.component) {
          ele.children.forEach(item => {
            // 将二级菜单的信息放入子路由中
            item.meta.parentName = ele.name
          })
        }
        rootEle.children = rootEle.children.concat(ele.children)
        delete ele.children
      }
    }
  })
}

function buildMenuRoutesStep3 (routes) {
  routes.forEach((ele, index) => {
    if (ele.children) {
      buildMenuRoutesStep3(ele.children)
    }
    if (!ele.component) {
      routes.splice(index, 1)
    }
  })
}

function loadConfigs () {
  // load api from config file
  Object.keys(window).forEach(key => {
    if (key.startsWith("$")) {
      if (window[key]) {
        util[key.slice(1)] = window[key]
      }
      delete window[key]
    }
  })
}

// 最大余额法 ， 保证百分比相加为100%
util.getPercentValue = function (valueList, idx, precision) {
  if (!valueList[idx]) {
    return 0
  }
  let sum = valueList.reduce(function (acc, val) {
    return acc + (isNaN(val) ? 0 : val)
  }, 0)
  if (sum === 0) {
    return 0
  }

  let digits = Math.pow(10, precision)
  let votesPerQuota = valueList.map((val) => {
    return ((isNaN(val) ? 0 : val) / sum) * digits * 100
  })
  let targetSeats = digits * 100
  let seats = votesPerQuota.map((votes) => Math.floor(votes))
  let currentSum = seats.reduce(function (acc, val) {
    return acc + val
  }, 0)

  let remainder = votesPerQuota.map((votes, idx) => votes - seats[idx])

  while (currentSum < targetSeats) {
    let max = -Infinity
    let maxId = null
    for (let i = 0; i < remainder.length; ++i) {
      if (remainder[i] > max) {
        max = remainder[i]
        maxId = i
      }
    }
    ++seats[maxId]
    remainder[maxId] = 0
    ++currentSum
  }
  return seats[idx] / digits
}

export default util
